/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.DepartmentEntity;
import entity.InternalMessageEntity;
import entity.SystemUserEntity;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import session.stateful.DepartmentSessionBean;

/**
 *
 * @author wei
 */
@Stateless
@LocalBean
public class InternalMessageSessionBean {

    @PersistenceContext
    EntityManager em;
    @EJB
    DepartmentSessionBean departmentManager;
    
    public InternalMessageEntity sendMessage(InternalMessageEntity message){
        message.setSentAt(new Date());
        return createOrUpdateMessage(message);
    }
    
    public InternalMessageEntity createOrUpdateMessage(InternalMessageEntity message, 
            List<Long> departmentIds){
        HashSet<SystemUserEntity> recipients = new HashSet<SystemUserEntity>();
        for(Long id : departmentIds){
            DepartmentEntity d = departmentManager.findDepartmentById(id);
            if(d == null)
                System.err.println("department not found: " + id);
            else
                recipients.addAll(d.getEmployees());
        }
        message.setRecipients(recipients);
        return createOrUpdateMessage(message);
    }
    
    public InternalMessageEntity createOrUpdateMessage(InternalMessageEntity message){
        InternalMessageEntity messageSaved = em.merge(message);
        em.flush();
        return messageSaved;
    }
}
